<?php

class TwoCheckoutController extends CustomControllerBase {
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		// Set page name
		$this->setPageName ( '2checkout_handler' );
	
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		$orderID = $this->getPost ( 'cart_order_id' );
		$isProcessed = $this->getPost ( 'credit_card_processed' );
		$url = $this->getApplicationUrl () . "Product/orderFail";
		// Processed
		if (! empty ( $orderID ) && ! empty ( $isProcessed ) && is_numeric ( $orderID ) && $isProcessed == "Y") {
			$customerOrderDataService = new CustomerOrderDataService ();
			$arrElement = array ();
			$arrElement ['id'] = intval ( $orderID );
			$arrElement ['payment_method'] = PAYMENT_2CHECKOUT;
			$results = $customerOrderDataService->getItems ( $arrElement );
			if (count ( $results ) > 0 && ! empty ( $results [0] )) {
				// Update order status
				$customerOrder = $results [0];
				$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
				$customerOrder->orders_status = ORDER_STATUS_PROCESSING;
				$customerOrderDataService->update ( $customerOrder );
				
				// Add order history
				$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
				$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
				$orderHistory->orders_id = $customerOrder->id;
				$orderHistory->date_added = date ( "Y-m-d H:i:s" );
				$orderHistory->comments = "";
				$orderHistory->orders_status = ORDER_STATUS_PROCESSING;
				$orderStatusHistoryDataService->create ( $orderHistory );
				
				// Empty cart
				$userCustomerBasketDataService = new UserCustomerBasketDataService ();
				$userCustomerBasketDataService->removeCart ( $customerOrder->customers_id, NULL );
				
				$url = $this->getApplicationUrl () . "Product/orderSuccess";
			}
		}
		
		CommonUtils::redirect ( $url );
	
	}
}
